package cn.bonoon.controllers.fmm;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.batatasframework.common.ParameterReader;
import org.batatasframework.manager.HtmlDetailBuilder;
import org.batatasframework.manager.RuntimeStrategyManaged;
import org.batatasframework.web.RequestParameterReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.web.controllers.AbstractLayoutController;

@Controller
@RequestMapping("s/sys/strategy")
public class PlatformStrategyController extends AbstractLayoutController{

	@Autowired(required = false)
	private Collection<RuntimeStrategyManaged> managers;
	
	@Override
	protected void onLoad(PanelEvent event) throws Exception {
		parse(event.getModel().getModelMap());
		event.setVmPath("sys/platform-strategy");
	}

	private void parse(ModelMap model){
		if(null != managers){
			List<HtmlDetailBuilder> items = new ArrayList<>(managers.size());
			for(RuntimeStrategyManaged manager : managers){
				items.add(manager.getHtmlBuilder());
			}
			model.addAttribute("items", items);
		}else{
			model.addAttribute("msg", "没有定义策略！");
		}
	}
	
	@RequestMapping(value = "!{key}/reset.do", method = POST)
	public String reset(ModelMap model, @RequestParam("id") String id){
		try{
			for(RuntimeStrategyManaged manager : managers){
				if(id.equals(manager.getId())){
					manager.reset();
					break;
				}
			}
			parse(model);
		}catch (Exception e) {
			log(e);
		}
		model.addAttribute("layout", "layout-empty.vm");
		return "sys/platform-strategy-items";
	}
	
//	@ResponseBody
	@RequestMapping(value = "!{key}/save.do", method = POST)
	public String save(ModelMap model, HttpServletRequest request, @RequestParam("id") String id){
		try{
			ParameterReader paraReader = RequestParameterReader.valueOf(request);
			for(RuntimeStrategyManaged manager : managers){
				if(id.equals(manager.getId())){
					manager.save(paraReader);
					break;
				}
			}
			parse(model);
		}catch (Exception e) {
			log(e);
		}
		model.addAttribute("layout", "layout-empty.vm");
		return "sys/platform-strategy-items";
	}

}
